package com.vehicle.common.util.thread.pool;


import com.vehicle.common.util.thread.NamedPoolThreadFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by yantingbin on 2017/7/29.
 */

public class DefaultExecutorFactory implements ExecutorFactory {

    private static final String V_EVENT_WORKER_MQ = "vehicle-event-worker-mq";
    private static final String V_EVENT_PUBLISH_MQ = "vehicle-event-publish-mq";
    @Override
    public Executor get(String name) {
        final ThreadPoolConfig config;
        switch (name) {
            case EVENT_WORKER_MQ:
                config = new ThreadPoolConfig.Builder(V_EVENT_WORKER_MQ)
                        .setCorePoolSize(Runtime.getRuntime().availableProcessors())
                        .setMaxPoolSize(16)
                        .setKeepAliceSeconds(TimeUnit.SECONDS.toSeconds(10))
                        .setQueueCapacity(10000)
                        .setRejectedPolicy(ThreadPoolConfig.REJECTED_POLICY_CALLER_RUNS).build();
                break;
            case EVENT_PUBLISH_MQ:
                config=new ThreadPoolConfig.Builder(V_EVENT_PUBLISH_MQ)
                        .setCorePoolSize(Runtime.getRuntime().availableProcessors())
                        .setMaxPoolSize(16)
                        .setKeepAliceSeconds(TimeUnit.SECONDS.toSeconds(10))
                        .setQueueCapacity(10000)
                        .setRejectedPolicy(ThreadPoolConfig.REJECTED_POLICY_CALLER_RUNS)
                        .build();
                break;
            default:
                throw new IllegalArgumentException("no executor for " + name);
        }
        return get(config);
    }

    private Executor get(ThreadPoolConfig config) {
        String name = config.getName();
        int corePoolSize = config.getCorePoolSize();
        int maxPoolSize = config.getMaxPoolSize();
        int keepAliveSeconds = config.getKeepAliceSeconds();
        BlockingQueue<Runnable> queue = config.getQueue();
        return new DefaultExecutor(corePoolSize
                , maxPoolSize
                , keepAliveSeconds
                , TimeUnit.SECONDS
                , queue
                , new NamedPoolThreadFactory(name)
                , new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
